<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24" v-if='isShow'>
            <a-form-model-item label="退货退款单编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="number">
              <a-input v-model="model.number" placeholder="请输入退货退款单编号" disabled ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="关联客户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerId">
              <JSelectMultiUser v-model="model.customerId" :query-config="selectUserQueryConfig" :url="kehuurl"  @change="kehuChange" :disabled='isAdd'/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="关联合同" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orderContactsIds">
              <relatecontract displayKey="name" v-model="model.orderContactsIds" :query-config="hetongConfig" :multiple="false"
                              :url="hetongurl"  @change="hetongChange" v-if='customerIdShow' :disabled='isAdd'></relatecontract>
              <span v-else>无</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="退货退款合同名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入退货退款合同名称"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="签订人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="signedBy">
              <j-select-user-by-dep v-model="model.signedBy" :multi="false" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="签订日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="signedTime">
              <j-date placeholder="请选择签订日期" v-model="model.signedTime"  style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="directorIds">
              <j-select-user-by-dep v-model="model.directorIds" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="协同人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="collaboratorIds">
              <j-select-user-by-dep v-model="model.collaboratorIds" :multi="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="退款产品" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="products" >
              <a-button class="editable-add-btn" @click="chanPinAdd(productRecordIds)" :disabled='isAdd'>
                添加产品
              </a-button>
              <a-table bordered
                       :dataSource="dataSource"
                       :columns="columns"
                       :pagination="false"
                       :scroll="{x:true}"
                       rowKey="id"
              >
                <template slot="name" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <template slot="number" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                规格-->
                <template slot="specifications" slot-scope="text, record,index">
                  <span>{{ text }}</span>
                </template>
                <!--                退货单位-->
                <template slot="unit" slot-scope="text, record">
                  <j-dict-select-tag type="list" v-model="text" dictCode="product_unit" disabled />
                </template>
                <!--                退货数量-->
                <template slot="num" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                退货单价-->
                <template slot="unitPrice" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                单价小计-->
                <template slot="quotedPriceTotal" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <!--                备注-->
                <template slot="remarks" slot-scope="text, record">
                  <span>{{ text }}</span>
                </template>
                <template slot="operation" slot-scope="text, record,index">
<!--                  <a @click="contactsEdit(record)">编辑</a>-->
<!--                  <a-divider type="vertical" />-->
                  <a @click="contactsDel(index)" :disabled='isAdd'>删除</a>
                </template>
              </a-table>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="退货金额总计" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="refundAmount">
              <a-input-number  v-model="model.refundAmount" placeholder="请输入退货金额总计" style="width: 100%"  :disabled='isAdd'/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="退货原因" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="refundReason">
              <j-search-select-tag v-model="model.refundReason" dict="refund_reason"  />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="退货备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-input v-model="model.remark" placeholder="请输入退货备注"  ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <productInfoModal ref="productInfo" @ok="productEditOK"></productInfoModal>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import JSelectMultiUser from '@/components/jeecgbiz/JSelectMultiUserCustom'
  import { validateDuplicateValue } from '@/utils/util'
  import relatecontract from '@/components/jeecgbiz/relatecontract/index'
  import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDepCustom'
  import JSelectUserByDepModalCustom from '@/components/jeecgbiz/modal/JSelectUserByDepModalCustom'
  import JSelectUserByDepCustom from '@comp/jeecgbiz/JSelectUserByDepCustom'
  import EditableCell from '@/components/EditableCell/cell'
  import moment from 'moment'
  import productInfoModal from '@comp/OrderProductInfo/ProductInfoModal'


  export default {
    name: 'RefundReturnForm',
    components: {
      JSelectMultiUser,
      relatecontract,
      JSelectUserByDepModalCustom,
      JSelectUserByDepCustom,
      JSelectUserByDep,
      EditableCell,
      productInfoModal
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    watch: {
      'model.customerId': {
        deep: true,
        handler(newValue, oldValue) {
          if (!newValue || newValue !== oldValue) {
            this.customerIdShow = false
          }
          if (newValue) {
            this.$nextTick(() => {
              this.customerIdShow = true
              this.kehuurl = '/customer/customer/list?filed=2&id=' + newValue
              if (this.model.orderContractId) {
                this.hetongurl = '/contractorder/contractOrder/list?customerId=' + newValue + '&id=' + this.model.orderContractId
              }
              else {
                this.hetongurl = '/contractorder/contractOrder/list?customerId=' + newValue
              }
            })
          }
        }
      },
      'model.orderContractId': {
        deep: true,
        handler(newValue, oldValue) {
          if (newValue) {
            this.$nextTick(() => {
              this.yingshoukuanurl = '/sys/common/queryByReceivables?id=' + newValue
            })
          }
        }
      },
      // 'model.refundAmount': {
      //   deep: true,
      //   immediate: false,
      //   handler(Nval, Oval) {
      //   }
      // },
      dataSource: {
        deep: true,
        immediate: true,
        handler(Nval, Oval) {
          this.totalProductsComputer()
        }
      }
    },
    data () {
      return {
        // htAmount:0,
        productRecordIds:'',//产品id集合
        htNumber:0,
        count: 1,
        isShow:false,
        isAdd:false,
        customerIdShow:false,
        dataSource: [],
        columns: [
          {
            title: '产品名称',
            dataIndex: 'name',
            key: 'name',
            scopedSlots: { customRender: 'name' }
          },
          {
            title: '产品编号',
            dataIndex: 'number',
            key: 'number',
            scopedSlots: { customRender: 'number' }
          },
          {
            title: '规格',
            dataIndex: 'specifications',
            key: 'specifications',
            scopedSlots: { customRender: 'specifications' }
          },
          {
            title: '退货单位',
            dataIndex: 'unit',
            key: 'unit',
            scopedSlots: { customRender: 'unit' }
          },
          {
            title: '退货数量',
            dataIndex: 'num',
            key: 'num',
            scopedSlots: { customRender: 'num' }
          },
          {
            title: '退货单价',
            dataIndex: 'unitPrice',
            key: 'unitPrice',
            scopedSlots: { customRender: 'unitPrice' }
          },
          {
            title: '单价小计',
            dataIndex: 'quotedPriceTotal',
            key: 'quotedPriceTotal',
            scopedSlots: { customRender: 'quotedPriceTotal' }
          },
          {
            title: '备注',
            dataIndex: 'remarks',
            key: 'remarks',
            scopedSlots: { customRender: 'remarks' }
          },
          {
            title: '操作',
            dataIndex: 'operation',
            key: 'operation',
            fixed: 'right',
            scopedSlots: { customRender: 'operation' }
          }
        ],
        kehuurl: '/customer/customer/list?filed=2',
        // 客户
        selectUserQueryConfig: [
          { key: 'phone', label: '电话' }
        ],
        //合同
        hetongurl: '/contractorder/contractOrder/list?filed=2'+'&customerId=',
        hetongConfig: [
          { key: 'number', label: '合同编号' }
        ],
        model:{
          signedTime:'',
          orderContactsIds:'',
          refundAmount:0,

         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
           number: [
              { required: true, message: '请输入退货退款单编号!'},
           ],
           customerId: [
              { required: true, message: '请选择关联客户!'},
           ],
           orderContactsIds: [
              { required: true, message: '请选择关联合同!'},
           ],
          name: [
            { required: true, message: '请输入退货退款单名称!'},
            {pattern:/^(?!(\s+$))/, message: '退货退款单名称不允许全为空格!'}
          ],
          directorIds: [
            { required: true, message: '请选择负责人!'},
          ],
          refundAmount: [
            { required: true, message: '请输入退货金额总计!'},
          ],
          refundReason: [
            { required: true, message: '请选择退货原因!'},
          ],
        },
        url: {
          add: "/refundreturn/refundReturn/add",
          edit: "/refundreturn/refundReturn/edit",
          queryById: "/refundreturn/refundReturn/queryById"
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      moment,
      kehuChange(e) {
        console.log("选择客户按钮",e)
        this.customerIdShow = false
        this.model.contactsIds = ''
      },
      hetongChange(e) {
        console.log("选择合同按钮",e)
        let orderContractId = e
        getAction('/contractorder/contractOrder/queryById?id='+ orderContractId ).then(res => {
          if (res.success) {
            let tempArr = res.result
            console.log('00000000000000000000',tempArr)
            let tempIdArr = tempArr.map(e =>{
              return e.productRecordIds
            })
            this.productRecordIds = tempIdArr
            console.log("this.productRecordIds",this.productRecordIds)
            let htje = tempArr.map(e =>{
              return e.contractAmount
            })
            this.htAmount = Number(htje)
            console.log("this.htAmount",this.htAmount)
          }
        })
      },
      //添加产品
      chanPinAdd(e) {
        this.$refs.productInfo.add(e)
      },
      //移除产品列表里的某一条产品
      contactsDel(index) {
        console.log(index)
        this.dataSource.splice(index, 1)
        this.model.products = this.dataSource
        //重新计算总价
        this.totalProductsComputer()
      },
      jpopCallBack(e) {
        console.log('e', e)
      },
      //总价计算
      totalProductsComputer() {
        const ageSum = this.dataSource.reduce((ageSum, e) => {
          return ageSum += Number(e.quotedPriceTotal)
        }, 0)
        this.model.refundAmount = ageSum
      },
      productEditOK(res) {
        console.log('添加产品返回数据', res)
        const { count, dataSource } = this
        if (res.key) {
          //编辑的情况
          const dataSource = [...this.dataSource]
          let target = dataSource.find((item) => item.key == res.key)
          target = Object.assign(target, res)
          this.dataSource = dataSource
        } else {
          //新增的情况
          let newData = Object.assign(res, { key: count })
          this.dataSource = [...this.dataSource, newData]
          this.count += 1
        }
        this.totalProductsComputer()
      },
      add () {
        this.edit(this.modelDefault);
        this.isShow = false
        this.isAdd = false
        this.model.signedTime = this.moment().format('YYYY-MM-DD')

      },
      edit (record) {
        this.isAdd = true
        this.model = Object.assign({}, record);
        let count = 0
        console.log('==========================================', record)
        if (record.products ) {
          if( record.products.length !== 0){
            record.products.map(res => {
              res.key = count += 1
              return res
            })
            console.log('编辑初始化产品列表', record.products)
            this.dataSource = record.products
          }else{
            console.log('elseeeeeeeeeeeeeeeeeeeeee')
          }

        }
        this.visible = true
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.model.products = this.dataSource
        this.model.products.forEach(e=>{
          let newArr = e
          newArr.orderContactsIds = this.model.orderContactsIds
        })
        console.log('productsssssssssssssss',this.model.products)
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
              method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
        })
      },
    }
  }
</script>